<template>
  <div class="app-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input
        v-model="listQuery.goodsSn"
        clearable
        size="mini"
        class="filter-item"
        style="width: 200px;"
        placeholder="请输入商品编号"
      />
      <el-input
        v-model="listQuery.barCode"
        clearable
        size="mini"
        class="filter-item"
        style="width: 200px;"
        placeholder="请输入商品条形码"
      />
      <el-input
        v-model="listQuery.goodsName"
        clearable
        size="mini"
        class="filter-item"
        style="width: 200px;"
        placeholder="请输入商品名称"
      />
      <el-button
        size="mini"
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >查找
      </el-button>
      <el-button
        size="mini"
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handlerAddPurchase"
      >添加进货
      </el-button>
    </div>

    <!-- 查询结果 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      size="small"
      element-loading-text="正在查询中。。。"
      border
      fit
      highlight-current-row
    >
      <el-table-column
        align="center"
        min-width="110"
        label="条形码"
        prop="barCode"
      />
      <el-table-column
        align="center"
        min-width="110"
        label="商品编号"
        prop="goodsSn"
      />
      <el-table-column
        align="center"
        min-width="200"
        label="名称"
        prop="goodsName"
      />

      <el-table-column
        align="center"
        property="picUrl"
        label="图片"
      >
        <template slot-scope="scope">
          <img
            :src="scope.row.picUrl"
            width="40"
          >
        </template>
      </el-table-column>

      <el-table-column
        align="center"
        label="商品规格"
        prop="specifications"
      />

      <el-table-column
        align="center"
        label="进货价"
        prop="purchasePrice"
      />

      <el-table-column
        align="center"
        label="进货数量"
        prop="purchaseNumber"
      />

      <el-table-column
        align="center"
        label="进货合计"
        prop="purchaseTotal"
        disabled="true"
      />

      <el-table-column
        align="center"
        label="供货商名称"
        prop="supplierName"
      />

      <el-table-column
        align="center"
        label="供货商电话"
        prop="supplierPhone"
      />

      <el-table-column
        align="center"
        label="进货日期"
        prop="purchaseTime"
      />

      <el-table-column
        align="center"
        label="赠品"
        prop="giftWare"
      >
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.giftWare"
            active-color="#13ce66"
            inactive-color="#494949"
            :active-value="1"
            :inactive-value="0"
            :disabled="true"
          />
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="操作"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <div class="button-container">
            <el-button
              type="info"
              size="mini"
              @click="handleUpdate(scope.row)"
            >编辑
            </el-button>
            <el-button
              type="danger"
              size="mini"
              @click="handleDelete(scope.row)"
            >删除
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <el-tooltip
      placement="top"
      content="返回顶部"
    >
      <back-to-top :visibility-height="100"/>
    </el-tooltip>

    <el-dialog :visible.sync="addPurchaseVisible" title="添加进货" :close-on-click-modal="false">
      <el-form
        ref="dataForm"
        :model="dataForm"
        status-icon
        label-position="left"
        label-width="100px"
        style="width: 100%;"
        :rules="rules"
      >
        <el-form-item label="所属商品">
          <el-select
            v-model="dataForm.productId"
            v-el-select-loadmore="loadMore"
            filterable
            clearable
            placeholder="请选择商品"
            style="width: 100%"
            @clear="remove()"
            @change="selectProduct"
          >
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="`${item.goodsName}-${item.specs}`"
              :value="item.id"
            >
              <span>{{ item.goodsName }}-{{ item.specs }}</span>
              <img :src="item.picUrl" style="height: 32px; float: right"/>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="进货价" prop="purchasePrice">
          <el-input v-model="dataForm.purchasePrice" @input="handleChangeTotal"/>
        </el-form-item>
        <el-form-item label="进货数量" prop="purchaseNumber">
          <el-input v-model="dataForm.purchaseNumber" @input="handleChangeTotal" type="number" min="1"/>
        </el-form-item>
        <el-form-item label="进货合计" prop="purchaseTotal">
          <el-input v-model="dataForm.purchaseTotal"/>
        </el-form-item>
        <el-form-item label="供货商名称" prop="supplierName">
          <el-input v-model="dataForm.supplierName"/>
        </el-form-item>
        <el-form-item label="供货商电话" prop="supplierPhone">
          <el-input v-model="dataForm.supplierPhone"/>
        </el-form-item>
        <el-form-item label="进货日期" prop="purchaseTime">
          <el-date-picker
            v-model="dataForm.purchaseTime"
            type="datetime"
            placeholder="选择日期"
            value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="赠品" prop="giftWare">
          <el-switch
            v-model="dataForm.giftWare"
            active-color="#13ce66"
            inactive-color="#494949"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addPurchaseVisible = false">取消</el-button>
        <el-button type="primary" @click="addPurchaseData">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import BackToTop from '@/components/BackToTop'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import { getToken } from '@/utils/auth'
import {
  addInventoryPurchase,
  deleteInventoryPurchase,
  listInventoryPurchase,
  updateInventoryPurchase
} from "@/api/business/inventory"
import { listProducts } from "@/api/business/goods"

export default {
  name: 'InventoryPurchaseList',
  components: { BackToTop, Pagination },
  directives: {
    "el-select-loadmore": {
      bind(el, binding) {
        // 获取element-ui定义好的scroll盒子
        const SELECTWRAP_DOM = el.querySelector(
          ".el-select-dropdown .el-select-dropdown__wrap"
        )
        SELECTWRAP_DOM.addEventListener("scroll", function() {
          const condition =
            this.scrollHeight - this.scrollTop <= this.clientHeight
          if (condition) {
            binding.value()
          }
        })
      }
    }
  },
  data() {
    return {
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10,
        goodsSn: '',
        productId: undefined,
        goodsName: undefined,
        sort: 'add_time',
        order: 'desc',
        barCode: ''
      },
      addPurchaseVisible: false,
      dataForm: {
        id: undefined,
        goodsId: undefined,
        productId: undefined,
        purchasePrice: 0.0,
        purchaseNumber: 1,
        purchaseTotal: '',
        supplierName: '',
        supplierPhone: '',
        purchaseTime: '',
        giftWare: 0,
        createTime: null,
        deleted: 0
      },
      options: [],
      formData: {
        page: 1,
        limit: 20,
        goodsId: null
      },
      props: { multiple: true, emitPath: false },
      rules: {
        goodsId: [{ required: true, message: "商品不能为空", trigger: "blur" }],
        purchaseNumber: [{ required: true, message: "进货数量不能为空", trigger: "blur" }],
        purchaseTime: [{ required: true, message: "进货日期不能为空", trigger: "blur" }],
        purchasePrice: [{ required: true, message: "进货价不能为空", trigger: "blur" }]
      },
      selectedItem: null
    }
  },
  computed: {
    headers() {
      return {
        'X-Dts-Merchant-Token': getToken()
      }
    }
  },
  created() {
    this.getList()
    this.getGoodList(this.formData)
  },
  methods: {
    handleChangeTotal() {
      this.dataForm.purchaseTotal = this.dataForm.purchaseNumber * this.dataForm.purchasePrice
    },
    addPurchaseData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          if (this.dataForm.id) {
            updateInventoryPurchase(this.dataForm).then((response) => {
              this.addPurchaseVisible = false
              this.$notify.success({
                title: "成功",
                message: "修改成功"
              })
              this.getList()
            })
              .catch((response) => {
                this.$notify.error({
                  title: "失败",
                  message: response.data.errmsg
                })
              })
          } else {
            addInventoryPurchase(this.dataForm).then((response) => {
              this.addPurchaseVisible = false
              this.$notify.success({
                title: "成功",
                message: "创建成功"
              })
              this.getList()
            })
              .catch((response) => {
                this.$notify.error({
                  title: "失败",
                  message: response.data.errmsg
                })
              })
          }

        }
      })

    },
    handlerAddPurchase() {
      this.addPurchaseVisible = true
    },
    remove() {
      this.dataForm.goodsValue = []
    },
    loadMore() {
      this.formData.page++
      this.getGoodList(this.formData)
    },
    getGoodList(formData) {
      this.listLoading = true
      listProducts(formData)
        .then((response) => {
          const _res = response.data.data.items
          this.options = [...this.options, ..._res]
          this.listLoading = false
        })
        .catch(() => {
          this.total = 0
          this.listLoading = false
        })
    },
    selectProduct(selVal) {
      this.dataForm.productId = Number(selVal)
      this.selectedItem = this.options.find(item => item.id == selVal)
      this.dataForm.goodsId = this.selectedItem?.goodsId
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    getList() {
      this.listLoading = true
      listInventoryPurchase(this.listQuery).then(response => {
        this.list = response.data.data.items
        this.total = response.data.data.total
        this.isAdmin = response.data.data.isAdmin
        this.listLoading = false
      }).catch(() => {
        this.list = []
        this.total = 0
        this.listLoading = false
      })
    },
    handleUpdate(row) {
      this.dataForm = row
      this.addPurchaseVisible = true
    },
    handleDelete(row) {
      this.$confirm("确定要删除吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          deleteInventoryPurchase(row).then((response) => {
            this.$notify.success({
              title: "成功",
              message: "删除成功"
            })
          }).catch((response) => {
            this.$notify.error({
              title: "失败",
              message: response.errmsg
            })
          })
        })
        .catch(() => {
        })
    }
  }
}
</script>

<style>
.el-dialog {
  width: 60%;
}

.table-expand {
  font-size: 0;
}

.table-expand label {
  width: 100px;
  color: #99a9bf;
}

.table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
}

.gallery {
  width: 80px;
  margin-right: 10px;
}

.htmlSpan {
  white-space: pre-wrap;
  word-break: break-all;
}
</style>
